<template>
    <div class='customDialog'>
        <div class="inStockDetail">
            <p style='font-size: 12px;margin-bottom: 10px;'>产品明细</p>
            <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" class="addProduct"
                @click="addOrEdit({title:'add'})">添加产品</el-button>

            <el-button size="mini" icon="el-icon-download" plain type='primary' @click="importModel('importMould')">导入数据
            </el-button>
            <!-- 列配置表格 -->
            <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup' style="float:right"></pop-checkbox>

            <el-table :data="computedPage" border style="width: 100%" ref="tabList"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" @cell-click='cellClick' :key="toUpdateTableKey">
                <el-table-column v-for="(item,index) in tableGroup" :key="item.label" :label="item.name"
                    show-overflow-tooltip :min-width="item.width"  :fixed="index <= 2"
                    >
                    <template slot-scope="scope">
                        <code v-if="item.label == 'handleNumber'">
                            <el-input-number v-model="scope.row.handleNumber" controls-position="right" size="mini"
                                :min="1" placeholder="请填写">
                            </el-input-number>
                        </code>
                        <code v-else-if="item.label == 'time'">
                            <el-date-picker v-model="scope.row.time" type="datetimerange" range-separator="至" 
                                start-placeholder="开始日期" format="yyyy-MM-dd HH:mm" :clearable='false' class='picker'
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </code>
                        <code v-else-if="item.label == 'workOrderCode' && $route.path != '/productionManagement/salesOrder/create'">
                            <div class="status">
                                <span :title="scope.row[item.label]">{{scope.row[item.label]}}</span>
                            </div>
                        </code>
                        <code v-else>
                            <code v-if='customImgSet(item.label, scope.row)'>
                                <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                    <img :src="$global.uploadUrl + k.url" alt=""
                                        v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i" class="customImg"
                                        @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'>
                                </p>
                                <p v-else>
                                    <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url"
                                        alt="" class="customImg"
                                        @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                    <span class='customImgMoreBox'>
                                        <div class='customImgMore'
                                            @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                            <el-popover placement="top" max-width="400" trigger="hover">
                                                <div class='customImgMore' slot="reference">
                                                    +{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                                <img :src="$global.uploadUrl + k.url" alt=""
                                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                    style="margin-right:10px" width='60px' height='60px'
                                                    @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))">
                                            </el-popover>
                                        </div>
                                        <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url"
                                            alt="" class="customImg">
                                    </span>
                                </p>
                            </code>
                            <code v-else>
                                <code v-if="customSelectSet(item.label, scope.row)">
                                    <span v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                        :style="customSelectStyle(item.label, scope.row, k)" class="customSelect">
                                        {{ k }}
                                    </span>
                                </code>
                                <code v-else style="overflow: hidden;text-overflow: ellipsis;">
                                    {{scope.row[item.label]}}
                                </code>
                            </code>
                        </code>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini"
                            @click="addOrEdit({title:'edit',row:scope.row,rowIndex:scope.$index})">编辑</el-button>
                        <el-button type="text" size="mini"
                            @click="copy(scope.$index)">复制</el-button>
                        <el-popconfirm placement='top' confirm-button-text='删除' title="确认删除产品？"
                            @confirm='delProduct(scope.$index,scope.row.id)'>
                            <el-button slot="reference" type="text" size="small" style="margin-left:10px">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
                <div slot="empty">
                    <el-empty :image-size="100"></el-empty>
                </div>
            </el-table>

            <el-pagination v-if="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :page-sizes="[10,20,50,100]" :page-size="pageSize" layout="total, prev, pager, next, sizes"
                :total="total" background>
            </el-pagination>

            <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
                <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial'
                    @change='handleCarousel' ref='carousel'>
                    <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                        <img :src="item.url" alt="" class='carouselImg'>
                    </el-carousel-item>
                </el-carousel>
                <div class='imgDownLoad' @click='imgDownLoad'>
                    <span class='el-icon-download'></span>
                    下载
                </div>
            </el-dialog>
        </div>

        <!-- 添加产品 -->
        <addOrEdit ref='addOrEdit' @getProductTable='getProductTable'></addOrEdit>

        <!-- 导入 -->
        <import-mould title='产品明细' ref='importMould' @importSuccess='importSuccess'></import-mould>

        <!-- 导入模板中有失败的数据时 -->
        <el-dialog :visible.sync="failVisible" width='520px' custom-class="failD">
            <div slot="title" class="fail">
                <el-result icon="success"></el-result>
                <div style="display: inline-block;">
                    <p style="font-size: 18px;">导入产品明细完成！</p>
                    <p style="font-size: 14px; opacity: 0.65;">成功{{successNum}}条,失败{{failNum}}条</p>
                </div>
            </div>
            <p style="font-size: 14px; opacity: 0.65;">以下为导入失败的产品明细：</p>
            <el-table :data="failData" border style="width: 100%"  max-height="220"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}">
                <el-table-column prop="productCode" label="产品编号">
                </el-table-column>
                <el-table-column prop="productName" label="产品名称">
                </el-table-column>
                <el-table-column prop="specification" label="产品规格">
                </el-table-column>
                <el-table-column label="失败原因">
                    <template slot-scope="scope">
                        <span style="color:red">{{scope.row.reason}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" plain @click="failVisible = false">知道了</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        pOther
    } from '@/api/baseController'
    import {
        productColumns
    } from '@/api/customFieldController'
    import addOrEdit from './addOrEdit.vue'
    export default {
        data() {
            return {
                productTable: [],
                failData:[],
                tableGroup: [],
                disposeGroup: [],
                toUpdateTableKey:false,
                customImgData: {
                    visible: false,
                    list: [],
                    title: '',
                    initial: 0,
                    num: 0
                },
                failVisible: false,
                index:0,
                successNum:0,
                failNum:0,
                productData: [],
                delId:[],
                cpOptions: [],
                currentPage: 1,
                total: 0,
                pageSize: 10,
            }
        },
        components: {
            addOrEdit
        },
        mounted() {
            this.getProductColumns({
                type: 'formInProduct'
            })
        },
        computed: {
            computedPage() {
                return this.productTable.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
            }
        },
        methods: {
            getProductColumns: async function(data){
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                            index:'80',
                            time:'380'
                        }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'formInProduct',
                    configureList
                }).then(()=>{
                    this.updateTable()
                })
            },
            // 导入
            importModel() {
                let obj = {
                    type: 'salesImportModel',
                    importUrl: '/produce/getByImportCode',
                    page: 'fromStock',
                    moduleType:1,
                    isCover: false
                }
                this.$refs.importMould.openDialog(obj)
            },
            // 导入成功
            importSuccess(payload) {
                if(!Object.keys(payload).length) return //导入空模板
                this.index ++ 
                let startTime = new Date().dateFormat('yyyy-MM-dd 00:00:00')
                let endTime = new Date().dateFormat('yyyy-MM-dd 23:59:59')
                if (payload.successData.length) { //导入模板中有成功的数据时
                    let productTable = []
                    payload.successData.forEach(i => {
                        i.customFieldVos = i.customFieldVos.filter(k => k.value.length)
                        i.customFieldVos.forEach(i => {
                            if (i.customFieldMess.fieldType == 'selectChecked') {
                                i.value = JSON.stringify(i.value.split(','))
                            }
                        })
                        productTable.push({
                            productCode: i.code,
                            productName: i.name,
                            productSpecification: i.specification || '-',
                            productId: i.id,
                            handleNumber: i.planedNumber || 1,
                            workOrderCode:'待生成',
                            time:[i.startTime == 'null' ? startTime : i.startTime,i.endTime == 'null' ? endTime : i.endTime],
                            customFieldVos: i.customFieldVos
                        })
                    })
                    this.getProductTable({
                        productTable,
                        title: '导入',
                    })
                    /**
                     * 初始化进入创建页面时，直接导入数据点击明细列表编辑无数据会报错，此时需要调用一下接口
                        拿到productData--cpOptions的值
                        后续在进行导入数据的操作时productData--cpOptions已经有值，无需再调用接口
                     */
                    if(this.index <= 1) this.getPOther({name:''}) //初始化进入创建页面 
                } 
                if (payload.errNum != 0) { //导入模板中有失败的数据时
                    this.failData = payload.failData
                    this.successNum = payload.successData.length
                    this.failNum = payload.failData.length
                    setTimeout(()=>{
                        this.failVisible = true
                    },400)
                }
            },
            getPOther(data) {
                pOther(data).then(res => { //当初始化导入数据的时候，点击编辑需要给productData--cpOptions赋值
                    if (res.code == 200) {
                        this.productData = res.data
                        this.cpOptions = res.data.map(item => {
                            return {
                                value: item.id,
                                label: item.code + '-' + item.name + '-' + item.specification
                            }
                        })
                        this.$refs.addOrEdit.getInfo(this.productData, this.cpOptions)
                    }
                })
            },
            addOrEdit(payload) {
                this.$refs.addOrEdit.add(payload)
            },
            //复制
            copy($index){
                let josnCopyItem = JSON.parse(JSON.stringify(this.productTable[$index]))
                josnCopyItem.index = this.productTable.length + 1
                josnCopyItem.workOrderCode = '待生成'
                if(josnCopyItem.id && this.$route.path == '/productionManagement/salesOrder/edit') delete josnCopyItem.id
                this.productTable = [...this.productTable,josnCopyItem]
                this.total = this.productTable.length
                this.$emit('productTableList', this.productTable)
            },
            //明细列表数据
            getProductTable(payload) {
                if (payload.title == '添加') {
                    this.productTable = [...this.productTable, payload.productTable]
                } else if (payload.title == '编辑') {
                    let editIndex = ((this.currentPage - 1) * this.pageSize) + payload.rowIndex
                    this.productTable.splice(editIndex, 1, payload.productTable)
                } else { //导入数据
                    this.productTable = [...this.productTable, ...payload.productTable]
                    if (payload.from == 'fromEdit') this.getPOther({
                        name: ''
                    })
                }
                this.productTable.forEach((item, i) => {
                    item.index = i + 1
                    if (item.customFieldVos != null) {
                        item.customFieldVos.forEach(k => {
                            item[k.customFieldId] = k.value
                            item.customType = k.customFieldMess.fieldType
                        })
                    }
                    this.total = this.productTable.length
                })
                this.$emit('productTableList', this.productTable)
            },
            //删除
            delProduct(index,id) {
                let totalPage = Math.ceil((this.total - 1) / this.pageSize)
                let currentPage = this.currentPage > totalPage ? totalPage : this.currentPage
                let delIndex = ((this.currentPage - 1) * this.pageSize) + index
                this.currentPage = currentPage < 1 ? 1 : currentPage
                this.productTable.splice(delIndex, 1)
                this.productTable.forEach((item, i) => {
                    item.index = i + 1
                    this.total = this.productTable.length
                })
                this.delId.push(id)
                this.delId = this.delId.filter(i => i != undefined)
                this.$emit('getDelId',this.delId)
                this.utils.showMsg('删除成功', 'success')
            },
            //跳转至详情页面
            cellClick(row, column) {
                if (column.label == '工单编号' && row.workOrderCode != '待生成') {
                    this.$router.push({
                        path: '/productionManagement/edit',
                        query:{
                            id: row.workOrderId,
                            code: row.workOrderCode,
                            state: row.workOrderState,
                            salesId: row.salesId,
                            salesCode: row.salesCode
                        }
                    })
                }
            },
            // 自定义字段 复选框/单选框 列
            customSelectSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if ((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess
                                    .fieldType == 'selectChecked') && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            customSelectList(t, d) {
                if (d[t] == '' || d[t] == '[]') {
                    return []
                } else {
                    let data = []
                    try {
                        data = JSON.parse(d[t])
                    } catch {
                        data = d[t].split(',')
                        data[0] == '' ? data = [] : ''
                    }
                    data === Number(data) ? data = [data] : ''
                    return data
                }
            },
            customSelectStyle(t, d, v) {
                let style = {}
                if (d.customFieldVos != null) {
                    let obj = d.customFieldVos.find(res => {
                        return res.customFieldId == t
                    })
                    if (obj.value != '' && obj.value != '[]') {
                        if (obj.customFieldMess.fieldType == 'selectRadio') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return obj.value == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                        if (obj.customFieldMess.fieldType == 'selectChecked') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return v == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                    }
                }
            },
            // 自定义字段图片列
            customImgSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if (item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            // 自定义图片预览
            costomImgPreview(i, len, list) {
                this.customImgData.visible = true
                this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
                this.customImgData.initial = Number(i) - 1
                this.customImgData.list = list.map(item => {
                    return {
                        name: item.name,
                        url: this.$global.uploadUrl + item.url
                    }
                })
                this.customImgData.num = i - 1
                this.setActiveItem(i - 1)
            },
            setActiveItem(i) {
                if (this.$refs.carousel) {
                    this.$refs.carousel.setActiveItem(i)
                }
            },
            // 图片预览轮播切换
            handleCarousel(v) {
                this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
                this.customImgData.num = v
            },
            // 图片下载
            imgDownLoad() {
                window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
            },
            //pageSize 改变时会触发
            handleSizeChange(val) {
                this.currentPage = 1
                this.pageSize = val
            },
            //currentPage 改变时会触发
            handleCurrentChange(val) {
                this.currentPage = val
            },
            updateTable() {
                this.toUpdateTableKey = !this.toUpdateTableKey
            }
        },
        beforeUpdate() {
            this.$nextTick(() => {
                this.$refs.tabList.doLayout()
            })
        }
    }
</script>

<style lang="less" scoped>
    .inStockDetail {

        code {
            font-family: sans-serif;
        }

        .addProduct {
            margin-bottom: 10px;
        }

        .icon-wenhao {
            margin-left: 2px;
            vertical-align: bottom;
        }
    }

    .el-dialog.failD {
        .el-dialog__header {
            .fail {
                width: 210px;
                height: 55px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                /deep/ .el-result {
                    padding: 0;
                    align-items: flex-start;

                    .el-result__icon svg {
                        width: 40px;
                        height: 40px;
                    }
                }
            }
        }
    }
    .status {
        span{
            display: inline-block;
            vertical-align: middle;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: #409EFF;
            cursor: pointer;
        }
    }
    .el-table td.el-table__cell .picker{
        height: 30px;
        line-height: 30px;
    }
    /deep/.el-date-editor .el-range__icon,/deep/ .el-date-editor .el-range-separator{
        line-height: 22px;
    }

    /deep/ .el-dialog__body {
        padding: 10px 20px;
    }

    /deep/ .el-dialog__footer {
        text-align: center;
    }

    /deep/ .el-select {
            width: 100%;
        }

    /deep/ .el-input-number--mini {
        width: 100%;
    }

    /deep/ .el-date-editor.el-input {
        width: 100%;
    }

    /deep/ .el-range-editor.el-input__inner {
        width: 100%;
    }
    /deep/ .el-range-editor .el-range-input {
        flex: 3;
    }
    /deep/ .el-date-editor .el-range-separator {
        flex: 1;
    }
</style>